package org.example.files.image;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "图片上传下载")
public class ImageController {

    @Value("${panda.file.image.path}")
    private String image_path;
    @PostMapping("/upload")
    public String uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传的文件为空";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(image_path +File.separator+ file.getOriginalFilename());
            if (path.getParent() != null) {
                Files.createDirectories(path.getParent());
            }
            Files.write(path, bytes);

            return "文件上传成功: " + file.getOriginalFilename();
        } catch (IOException e) {
            return "文件上传失败: " + e.getMessage();
        }
    }

    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<ByteArrayResource> downloadImage(@PathVariable String filename) {
        if (filename == null || filename.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        Path file = Paths.get(image_path +File.separator+ filename);
        if (!Files.exists(file)) {
            return ResponseEntity.notFound().build();
        }


        try {
            byte[] data = Files.readAllBytes(file);
            ByteArrayResource resource = new ByteArrayResource(data);

            return ResponseEntity.ok()
                    .headers(headers())
                    .contentLength(data.length)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    private HttpHeaders headers() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "downloaded-file.jpg" + "\"");
        return headers;
    }
}
